/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.service.product;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.modules.ivm.dao.product.ProductUnitDao;
import com.neusoft.lohas.modules.ivm.entity.product.ProductUnit;
import com.neusoft.lohas.modules.ivm.utils.ProductUtils;

/**
 * 商品单位Service
 * @author Jackie.Liu
 * @version 2014-10-30
 */
@Component
@Transactional(readOnly = true)
public class ProductUnitService extends BaseService {

	@Autowired
	private ProductUnitDao productUnitDao;
	
	public ProductUnit get(String id) {
		return productUnitDao.get(id);
	}
	
	public Page<ProductUnit> find(Page<ProductUnit> page, ProductUnit productUnit) {
		DetachedCriteria dc = productUnitDao.createDetachedCriteria();
		if (StringUtils.isNotEmpty(productUnit.getName())){
			dc.add(Restrictions.like("name", "%"+productUnit.getName()+"%"));
		}
		dc.add(Restrictions.eq(ProductUnit.FIELD_DEL_FLAG, ProductUnit.DEL_FLAG_NORMAL));
		dc.add(Restrictions.eq("merchant.id", productUnit.getMerchant().getId()));
		dc.add(Restrictions.eq("type", productUnit.getType()));
		dc.addOrder(Order.asc("sort"));
		return productUnitDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(ProductUnit productUnit) {
		productUnitDao.save(productUnit);
		ProductUtils.removeCache(ProductUtils.CACHE_UNIT_LIST);
		ProductUtils.removeCache(ProductUtils.CACHE_SPEC_LIST);
	}
	
	@Transactional(readOnly = false)
	public void delete(String id) {
		productUnitDao.deleteById(id);
		ProductUtils.removeCache(ProductUtils.CACHE_UNIT_LIST);
	}

	public ProductUnit findByName(String type, String name, String mId) {
		return productUnitDao.findByName(type, name, mId);
	}
	
}
